var isStarted = false;

mainEntrence();

// 程序主入口
function mainEntrence() {
  deviceInfo();
  eventListener();
  sleep(600);

  // 选关卡
  //beforeRun();
  //while (true) {
  // 运行主函数
  main();
  //}
}


function eventListener() {
  threads.start(function () {
    // 启用按键监听
    events.observeKey();
    // 监听音量上键按下
    events.onKeyDown("volume_down", function (event) {
      toastLog("程序手动退出");
      threads.shutDownAll();
      exit();
    });
  });
}


function deviceInfo() {
  auto();
  if (!requestScreenCapture()) {
    toast('请求截图失败，程序结束');
    exit();
  }
}

function main() {
  toast("开始运行");

  sleep(1000);
  clickContinue();
  sleep(2000);
  checkTouchDrive();
  // 开始
  click(2400, 1280);
  sleep(1000);
  clickContinue();
  sleep(5000);

  // 开跑
  runUtilEnd();

  // 跑完之后

}

function runUtilEnd() {
  toast("开始");
  var isEnd = false;
  do {
      sleep(1000);
      var continueBtn = getPointColor(captureScreen(), 2270, 1260);
      if (colors.isSimilar(continueBtn, "#ffc3fb12")) {
          isEnd = true;
      } else {
        swipe(1960, 720, 1000, 720, 300);
        swipe(1960, 720, 1000, 720, 300);
        click(2490, 1120);
      }
  } while (!isEnd);
  afterRun();
}

function afterRun() {
  toast("跑完了");
  sleep(1000);
  clickContinue();
  sleep(2000);
  var img = captureScreen();
  var continueBtn = getPointColor(captureScreen(), 2380, 1260);
  if (colors.isSimilar(continueBtn, "#ffc3fb12",10)) {
    clickContinue();
    sleep(4000);
    clickContinue();
    sleep(2000);
    clickContinue();
  } else {
    sleep(5000);
  }

  var home = false;
    do {
        clickContinue();
        sleep(5000);
        var leftTop = getPointColor(captureScreen(), 100, 100);
        home = colors.isSimilar(leftTop, "#ffffff", 8);
    } while (!home);
  main();

}

function clickContinue() {
  click(2500, 1260);
}

function checkTouchDrive() {
  sleep(1000);
  var tdPoint = findColor(captureScreen(), "#ffc0f814", {
      region: [2700, 1060, 120, 100],
      threshold: 10
  });
  toast(tdPoint);
  if (!tdPoint) {
      toast("打开自动驾驶");
      click(2700, 1100);
      sleep(2000);
  }
}

function checkForResolution(x, y, img) {
  var width = img.getWidth();
  var height = img.getHeight();
  if (width < height) {
    var e = x;
    x = y;
    y = e;
  }

  return {
    positionX: x,
    positionY: y
  };
}

function getPointColor(img, x, y) {
  var data = checkForResolution(x, y, img);
  return images.pixel(img, data.positionX, data.positionY);
}